package lock_thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/29
 * Time:21:13
 * synchronized修饰代码块、静态方法
 **/
public class Demo5 {

    //全局变量
    private static int number = 0;
    //循环次数
    public static final int maxSize = 100000;

    public synchronized void increment() {
        for (int i = 0; i < maxSize; i++) {
            //实现加锁
            number++;
        }
    }

    public synchronized void decrement() {
        for (int i = 0; i < maxSize; i++) {
            //实现加锁
            number--;
        }
    }

    public static void main(String[] args) throws InterruptedException {

        Demo5 demo5 = new Demo5();

        //+10W
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                demo5.increment();
            }
        });
        t1.start();

        //-10W
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                demo5.decrement();
            }
        });
        t2.start();

        //等待线程1 线程2执行完
        t1.join();
        t2.join();

        System.out.println("最终执行结果" + number);

        /*public static synchronized void increment{
            for (int i = 0; i < maxSize; i++) {
                number++;
            }
        }

        public static synchronized void decrement{
            for (int i = 0; i < maxSize; i++) {
                number--;
            }
        }
        Thread t1 = new Thread(runnable, "t1");
        Thread t2 = new Thread(runnable, "t2");

        Thread.sleep(10);
        t1.start();
        t2.start();*/
    }
}
